/*
 * DBuscar.java
 *
 * Created on 16 de mayo de 2006, 03:18 PM
 */

package ig.metrica.ui.matrizcorrelacion;

import ejb.metrica.matriz.correlacion.MatrizCorrelacionSBBean;
import ejb.metrica.matriz.correlacion.MatrizDTO;
//import ig.metrica.riesgo.MatrizCorrelacion;
//import ig.metrica.riesgo.MatrizCorrelacionHome;
import ig.metrica.ui.interfaces.comunes.IMetodosPantallas;
import ig.metrica.ui.interfaces.comunes.IModelo;
import ig.util.MyTableModel;
import ig.util.NoContinuaException;
import java.awt.Component;
import java.rmi.RemoteException;
import java.util.Collection;
import javax.naming.NamingException;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author  jsanchez
 */
public class DBuscar extends javax.swing.JDialog implements IMetodosPantallas{
    
    //ModeloMatrizCorrelacion modelo=null;
    IModelo modelo=null;
    MyTableModel myTableModel =null;
    /** Creates new form PBsucarUsuario */
//    ManipulacionDatos mpd=null;
    String[] Columnas ={"ID", "Nombre"};
    Object [][] Datos=null;
    boolean[] Editables = {false, false, false, false};
    int tM=0;
    public DBuscar(IModelo modelo) throws NoContinuaException{
        super(
                (modelo instanceof ModeloMatrizCorrelacion)?
                ((ModeloMatrizCorrelacion)modelo).getRootPanel():
            ((modelo instanceof ModeloEscaleraDeBandas)?
                ((ModeloEscaleraDeBandas)modelo).getRootPanel():null),
            true);

        tM=(modelo instanceof ModeloMatrizCorrelacion)?0:1;

        myTableModel= new MyTableModel(Datos,Columnas,Editables);
        initComponents();
        this.Tabla.getTableHeader().setReorderingAllowed(false);
        this.modelo=modelo;
        centrar();
        this.buscar();
        this.setVisible(true);        
    }
    
    public void centrar() {
        java.awt.Dimension dimensionScreen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Rectangle dimensionPantalla = getBounds();
        setLocation((dimensionScreen.width - dimensionPantalla.width) / 2, (dimensionScreen.height - dimensionPantalla.height) / 2);
    }
    
    
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        Tabla = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        Buscar = new javax.swing.JButton();
        Aceptar = new javax.swing.JButton();
        Cancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        Tabla.setModel(this.myTableModel);
        Tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TablaMouseClicked(evt);
            }
        });

        jScrollPane1.setViewportView(Tabla);

        jToolBar1.setEnabled(false);
        Buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/util/images/buscar.gif")));
        Buscar.setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 6, 6, 6));
        Buscar.setOpaque(false);
        Buscar.setPreferredSize(new java.awt.Dimension(43, 43));
        Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuscarActionPerformed(evt);
            }
        });

        jToolBar1.add(Buscar);

        Aceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/util/images/aceptar.gif")));
        Aceptar.setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 6, 6, 6));
        Aceptar.setOpaque(false);
        Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AceptarActionPerformed(evt);
            }
        });

        jToolBar1.add(Aceptar);

        Cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/util/images/salir.gif")));
        Cancelar.setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 6, 6, 6));
        Cancelar.setOpaque(false);
        Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelarActionPerformed(evt);
            }
        });

        jToolBar1.add(Cancelar);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(12, 12, 12)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)
                .add(12, 12, 12))
            .add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(5, 5, 5)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        
    }//GEN-LAST:event_formWindowClosing
    
    private void CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarActionPerformed
        try {
            this.salir();
        } catch (NoContinuaException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_CancelarActionPerformed
    
    private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AceptarActionPerformed
        this.aceptar();
    }//GEN-LAST:event_AceptarActionPerformed
    
    private void BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarActionPerformed
        try {
            this.buscar();
        } catch (NoContinuaException ex) {
            JOptionPane.showMessageDialog(this,ex.getMessage(),"Mensaje",JOptionPane.OK_OPTION);
        }
    }//GEN-LAST:event_BuscarActionPerformed
    
    private void TablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaMouseClicked
        if(evt.getClickCount()==2){//Doble click en la tabla
            this.aceptar();
        }
    }//GEN-LAST:event_TablaMouseClicked
    
    public JInternalFrame getInternalFrame() {
        return null;
    }
    
    public void validar() throws NoContinuaException {
    }
    
    public void guardar() throws NoContinuaException {
    }
    //String[] Columnas ={"Usuario", "Tipo", "Nombres", "Apellidos"};
    Object[] data= null;
    private Collection CBusqueda=null;
    public void buscar() throws NoContinuaException {
        try {
            CBusqueda=this.lookupMatrizCorrelacionSBBean().findAll();
            
            int j=0;
            for (Object elem : CBusqueda) {
                if(((MatrizDTO)elem).getTipo().equals(tM)){
                    j++;
                }
            }
            Datos= new Object[j][2];
            j=0;
            for (Object elem : CBusqueda) {
                if(((MatrizDTO)elem).getTipo().equals(tM)){
                    Datos[j][0]=((MatrizDTO)elem).getId();
                    Datos[j][1]=elem;
                    j++;
                }
            }
            ((MyTableModel)this.Tabla.getModel()).setData(Datos);
            this.Tabla.updateUI();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
//        ctx =null;
//        home=null;
    }
    
    public void modificar() throws NoContinuaException {
    }
    
    public void nuevo() throws NoContinuaException {
    }
    
    public void eliminar() throws NoContinuaException {
    }
    
    public void salir() throws NoContinuaException {
        this.dispose();
        if(modelo instanceof ModeloMatrizCorrelacion)
          ((ModeloMatrizCorrelacion)modelo).setEstado();
    }
    
    public void imprimir() throws NoContinuaException {
    }
    
    public void cancelar() throws NoContinuaException {
    }
    
    public Component[] getControles() {
        return null;
    }
    
    public void setFrame(JFrame frame) {
    }
    
    public JFrame getFrame() {
        return null;
    }
    
    private void aceptar() {
        if(CBusqueda!=null){
            if(this.Tabla.getSelectedRow()!=-1){
//                modelo.setId(Integer.valueOf(this.Tabla.getModel().getValueAt(this.Tabla.getSelectedRow(),0).toString()));
               if(modelo instanceof ModeloMatrizCorrelacion){
                    ((ModeloMatrizCorrelacion)modelo).setDTO((MatrizDTO) this.Tabla.getModel().getValueAt(this.Tabla.getSelectedRow(),1));
               }else{
                    ((ModeloEscaleraDeBandas)modelo).setId(Integer.valueOf(this.Tabla.getModel().getValueAt(this.Tabla.getSelectedRow(),0).toString()));
               }
                this.dispose();
                try {
                    modelo.buscar();
                } catch (NoContinuaException ex) {
                    ex.printStackTrace();
                }
            }else
                JOptionPane.showMessageDialog(this,"No se ha seleccionado ninguna Matriz de correlaci\u00F3n","Mensaje",JOptionPane.OK_OPTION);
        }
    }
    private ejb.metrica.matriz.correlacion.MatrizCorrelacionSBBean lookupMatrizCorrelacionSBBean() {
    
        return new MatrizCorrelacionSBBean();
        /*try {
            Properties prop = new Properties();
            prop.put( Context.INITIAL_CONTEXT_FACTORY, IGBean.INITIAL_CONTEXT_FACTORY);
            String Sockec = new ConexionServer().getSocketServer();
            prop.put( Context.PROVIDER_URL, Sockec);
            javax.naming.Context c = new javax.naming.InitialContext(prop);
            Object remote = c.lookup("MatrizCorrelacionSBBean");
            ejb.metrica.matriz.correlacion.MatrizCorrelacionSBRemoteHome rv = (ejb.metrica.matriz.correlacion.MatrizCorrelacionSBRemoteHome) javax.rmi.PortableRemoteObject.narrow(remote, ejb.metrica.matriz.correlacion.MatrizCorrelacionSBRemoteHome.class);
            return rv.create();
        } catch(javax.naming.NamingException ne) {
//            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ne);
            throw new RuntimeException(ne);
        } catch(javax.ejb.CreateException ce) {
//            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ce);
            throw new RuntimeException(ce);
        } catch(java.rmi.RemoteException re) {
//            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,re);
            throw new RuntimeException(re);
        }*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Aceptar;
    private javax.swing.JButton Buscar;
    private javax.swing.JButton Cancelar;
    private javax.swing.JTable Tabla;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
    
}
